import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";


//游戏控制器
class GameControl{
    // 定义三个属性
    snake:Snake;
    food:Food;
    scorelpanel:ScorePanel;

    //创建一个属性来存储蛇的移动方向
    direction: string = "";

    // 判断是否存活
    isLive = true;

    constructor() {
        this.snake = new Snake();
        this.food = new Food();
        this.scorelpanel = new ScorePanel(20,4);
        this.init()
    }
    // 游戏的初始化方法，调用后游戏开始
    init(){
        document.addEventListener("keydown", this.keydownHandler.bind(this) )
         this.run()
    }

    // 创建一个键盘按下的响应函数
    keydownHandler(event: KeyboardEvent){
        this.direction = event.key;
    }

    //创建一个蛇移动的方法
    run(){
        /**
         * 根据direction来使蛇的位置改变
         * 向上 top 减少
         * 向下 top 增加
         * 向左 left 减少
         * 向右 left 增加
         */
        // 获取蛇的坐标
        let x = this.snake.X
        let y = this.snake.Y

        switch (this.direction){
            case "ArrowUp":
            case "UP":
                y -= 10;
                break
            case "ArrowDown":
            case "Down":
                y += 10;
                break
            case "ArrowLeft":
            case "Left":
                x -= 10;
                break
            case "ArrowRight":
            case "Right":
                x += 10;
                break
        }

        this.checkEat(x,y)


        try{
            this.snake.X = x;
            this.snake.Y = y;
        }catch (e){
            alert(e.message);
            this.isLive = false;
        }


        this.isLive && setTimeout(this.run.bind(this),300 - (this.scorelpanel.level-1)*30)
    }

    checkEat(x:number, y:number){
        console.log("蛇"+x,y)
        console.log("食物"+this.food.x,this.food.y)
         if (x === this.food.x && y === this.food.y){
             console.log("加载食物")
             // 重新加载食物
             this.food.change();

             // 分数加一
             this.scorelpanel.addScore();

             // 添加身体
             this.snake.addBody();
         }
        }
}


export default GameControl;